var express = require('express');
const mongoose = require('mongoose')
const db = require('../mongodb/db');
const md5 =require('md5')
const usermodel = require('../mongodb/models/usermodel');
var router = express.Router();


db(() => {

})
/* GET users listing. */
router.get('/reg', function(req, res, next) {
  res.render('reg')
  return
});
router.get('/login', function(req, res, next) {
  res.render('login')
  return
});
router.post('/reg', function(req, res, next) {
  usermodel.create({username:req.body.username,password:md5(req.body.password)},(err,data)=>{
    if(err){
      return res.statusCode(500).send('注册失败')
    }

    res.render('success')

    /* res.json({
      code:'0000',
      msg:'注册成功',
      data:data,
    }) */
  })
  return

});
router.post('/login',function(req,res,next){
  let {username,password}=req.body
  usermodel.findOne({username:username,password:md5(password)},(err,data)=>{
    if(err){
      return res.statusCode(500).send('登录失败')
    }
    if(!data){
        res.render('loginerror')
      return 
    }
    req.session.username=data.username
    req.session._id=data._id
    req.session.ifapply=data.ifapply

    res.redirect('/prehome')
  })
  return

})
router.get('/logout',(req,res)=>{
  req.session.destroy(()=>{
    res.render('login')
  })
  return
})
module.exports = router;
